package slidingWindowAlgorithm.re11_01;

import java.util.HashMap;

public class Class567 {

    public boolean checkInclusion(String s1, String s2) {
       boolean ans=false;
        HashMap<Character, Integer> need = new HashMap<>();
        for (int i = 0; i < s1.length(); i++) {
            need.put(s1.charAt(i),need.getOrDefault(s1.charAt(i),0)+1);
        }
        int left=0,right=0;
        int valid=0;
        HashMap<Character, Integer> window = new HashMap<>();
        while (right<s2.length()){
            char c = s2.charAt(right);
            right++;
            if (need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0)+1);
                if (window.get(c).equals(need.get(c))){
                    valid++;
                }
            }
            int size = need.size();
            //TODO:2023/11/1 此处应该用while 一直循环下去
            while (valid==size){
                char c1 = s2.charAt(left);
                left++;
                if (need.containsKey(c1)){
                    //TODO:2023/11/1   有可能need里需要的字符对应的值是比所需要的多的
                    //TODO:2023/11/1 所以就先判断是否window里面的c1数值是否刚好等于need里面所需要的数值
                    if (window.get(c1).equals(need.get(c1))){
                        valid--;
                    }
                    window.put(c1,window.get(c1)-1);
                }
                if (valid!=size){
                    if (right-left+1==s1.length()){
                        ans=true;
                        return  ans;
                    }
                }
            }
      }
       return  ans;
    }
}
